{% extends 'base.html' %} {% block head %} {{ super() }}
{% if not current_app.debug %}
    <!-- codemirror -->
    <link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.58.3/codemirror.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.58.3/theme/darcula.min.css" rel="stylesheet">
    <!-- <link href="//vjs.zencdn.net/7.8.2/video-js.min.css" rel="stylesheet">
    <script src="//vjs.zencdn.net/7.8.2/video.min.js"></script> -->
    <!-- 视频播放 -->
    <link href="{{ url_for('static', filename='css/videojs.css') }}" rel="stylesheet">
{% else %}
    <!-- codemirror -->
    <link href="{{ url_for('static', filename='codemirror/codemirror.css') }}" rel="stylesheet" />
    <link href="{{ url_for('static', filename='codemirror/theme/darcula.css') }}" rel="stylesheet" />
    <!-- 视频播放 -->
    <link href="{{ url_for('static', filename='css/videojs.css') }}" rel="stylesheet">
{% endif %}
{% endblock %} {% block title %}主页{% endblock %} {% block content %}
<!-- Page Heading -->
<!-- <h1 class="h3 mb-2 text-gray-800">Tables</h1>
<p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> -->
<div id="action" class="mb-4" style="display: none;">
  <a class="btn btn-primary btn-user" onclick="upload()" style="color: #fff;margin-top: 7px;"><i class='fas fa-arrow-up'></i>&ensp;上传</a>
  <a class="btn btn-primary btn-user" onclick="mkdir()" style="color: #fff;margin-top: 7px;"><i class='fas fa-folder'></i>&ensp;新建文件夹</a>
  <a class="btn btn-primary btn-user" onclick="touch()" style="color: #fff;margin-top: 7px;"><i class='fas fa-file'></i>&ensp;新建文件</a>
  <div class="dropdown" style="display: inline-block;top: 3px;z-index: 0;" id="actiondropdown" >
    <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <i class='fas fa-bars'></i>&ensp;
      操作
    </button>
    <div class="dropdown-menu animated--fade-in" aria-labelledby="dropdownMenuButton">
      <a class="dropdown-item" href="#" onclick="copy()"><i class='fas fa-copy'></i>&ensp;复制</a>
      <a class="dropdown-item" href="#" onclick="cut()"><i class='fas fa-cut'></i>&ensp;剪切</a>
      <a class="dropdown-item" href="#" onclick="zip()"><i class='fas fa-sticky-note'></i>&ensp;压缩</a>
      <a class="dropdown-item" href="#" onclick="deletes()"><i class='fas fa-trash'></i>&ensp;删除</a>
    </div>
  </div>
  <a class="btn btn-primary btn-user" style="color: #fff;display: none;margin-top: 7px;" onclick="paste()" id="paste"><i class='fas fa-paste'></i>&ensp;粘贴</a>
</div>
<!-- DataTales Example -->
<div class="card shadow mb-4">
  <div class="card-header py-3">
    <h6 class="m-0 font-weight-bold text-primary" id="fileroute"><a href="javascript:void(0);">全部文件</a></h6>
  </div>
  <div class="card-body">
    <div class="table-responsive">
      <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
        <thead>
          <tr>
            <th>
              <input type="checkbox" class="checkall" />
            </th>
            <th class="sorting">文件名</th>
            <th class="sorting">大小</th>
            <th class="sorting">权限</th>
            <th class="sorting">修改时间</th>
            <th class="sorting">操作</th>
          </tr>
        </thead>
      </table>
    </div>
  </div>
</div>
<!-- 模态框（Modal）文本编辑 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      </div>
      <div class="modal-body">
        <span id="textTitle" style="display: none"></span>
        <textarea id="FunctionEditor"></textarea>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" id="submitText">提交更改</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal -->
</div>
<!-- 模态框（Modal）文件分享 -->
<div class="modal fade" id="myModalShare" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      </div>
      <div class="modal-body">
        <form class="user" id="shareform" action="{{ url_for('share.create') }}" method="post">
          <input type="text" name="filename" id="filenames" value="" style="display: none" />
          <div class="form-group">
            <span>有效期：</span>
            <label class="radio-inline"> <input type="radio" name="validdate" id="optionsRadios3" value="" /> 永久 </label>
            <label class="radio-inline"> <input type="radio" name="validdate" id="optionsRadios4" value="7" checked /> 7天 </label>
            <label class="radio-inline"> <input type="radio" name="validdate" id="optionsRadios4" value="1" /> 1天 </label>
          </div>
          <div class="form-group" style="word-wrap: break-word;word-break: normal;">
            <a id="link" target="_blank" style="display: none"></a>
          </div>
          <div class="form-group row">
            <div class="col-sm-6 mb-3 mb-sm-0">
              <input id="editcode" type="text" class="form-control form-control-user" placeholder="为空则不设置提取码" name="getcode" />
            </div>
            <div class="col-sm-6">
              <a class="btn btn-primary btn-user btn-block" id="bulidcode" style="color: #fff">生成提取码</a>
            </div>
          </div>
          <div class="form-group">
            <a class="btn btn-primary btn-user btn-block" id="copylink" style="color: #fff; display: none">复制链接</a>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" id="submitShare">生成连接</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal -->
</div>
<!-- 模态框（Modal）文件上传 -->
<div class="modal fade" id="myModalupload" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      </div>
      <div class="modal-body">
        <input id="fileupload" type="file" name="file" multiple style="display: none;"/> 
        <div id="uploads" style="height: 330px;border: 2px dashed #0087F7; margin: 7.5px;overflow: auto;">
        </div>
        <div class="progress progress-sm mb-2">
          <div class="progress-bar" role="progressbar" style="width: 0%;display: none;" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" id="submitUploaddn">取消上传</button>
        <button type="button" class="btn btn-primary" id="submitUpload">开始上传</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal -->
</div>
<!-- 模态框（Modal）视频播放 -->
<div class="modal fade" id="myModalvideo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content" style="background-color: transparent;border: none;">
        <video
            id="my-player"
            class="video-js"
            controls
            preload="auto"
            width="100%"
            height="auto"
            data-setup='{}'>
          <source src="" type="video/mp4"></source>
          <p class="vjs-no-js">
            你的浏览器不支持播放视频
            <a href="https://videojs.com/html5-video-support/" target="_blank">
              查看支持的浏览器
            </a>
          </p>
        </video>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal -->
</div>
<!-- 图片浏览盒子 -->
<div><img id="imageview" src="" alt="Picture" style="display: none" /></div>

{% endblock %} {% block scripts %} {{ super() }}
{% if not current_app.debug %}
    <!-- 代码编辑器 https://github.com/codemirror/CodeMirror -->
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.58.3/codemirror.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.58.3/mode/python/python.min.js"></script>
    <!-- 视频播放 https://github.com/videojs/video.js -->
    <script src="{{ url_for('static', filename='js/video.js') }}"></script>
    <!-- 文件上传 https://github.com/blueimp/jQuery-File-Upload -->
    <script src="{{ url_for('static', filename='js/jquery.ui.widget.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.iframe-transport.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.fileupload.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.fileupload-process.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.fileupload-validate.js') }}"></script>
    <!-- base64编码转换 https://github.com/dankogai/js-base64 -->
    <script src="https://cdn.jsdelivr.net/npm/js-base64@3.6.0/base64.min.js"></script>
{% else %}
    <!-- 代码编辑器 https://github.com/codemirror/CodeMirror -->
    <script src="{{ url_for('static', filename='codemirror/codemirror.js') }}"></script>
    <script src="{{ url_for('static', filename='codemirror/mode/python/python.js') }}"></script>
    <!-- 视频播放 -->
    <script src="{{ url_for('static', filename='js/video.js') }}"></script>
    <!-- 文件上传 -->
    <script src="{{ url_for('static', filename='js/jquery.ui.widget.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.iframe-transport.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.fileupload.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.fileupload-process.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.fileupload-validate.js') }}"></script>
    <!-- base64编码转换 https://github.com/dankogai/js-base64 -->
    <script type="text/javascript" src="{{ url_for('static',filename='js/base64.js') }}"></script>
{% endif %}
<script>
  $(function () {
    //选中菜单栏中的选项
    $('#file-page').attr('class','nav-item active')
  })

  var nowPath = ''
  var sep = Base64.decode('{{sep}}')
  var workPath = ''

  //表格(DataTables)-4，综合示例
  var language = {
    search: '搜索：',
    lengthMenu: '每页显示 _MENU_ 记录',
    zeroRecords: '没找到相应的数据！',
    info: '分页 _PAGE_ / _PAGES_',
    infoEmpty: '暂无数据！',
    infoFiltered: '(从 _MAX_ 条数据中搜索)',
    paginate: {
      first: '首页',
      last: '尾页',
      previous: '上一页',
      next: '下一页',
    },
  }

  var filetype
  var urldir = "{{ url }}"

  $('#dataTable').dataTable({
    autoWidth: false,
    lengthChange: true, //不允许用户改变表格每页显示的记录数
    pageLength: 10, //每页显示几条数据
    lengthMenu: [5, 10, 20, 40], //每页显示选项
    pagingType: 'full_numbers',
    // bStateSave: true,
    ajax: {
      url: urldir,
      type: 'POST',
      // 传给服务器的数据，可以添加我们自己的查询参数
      data: function (param) {
        //param.path = Base64.encode(nowPath)
        return param
      },
    },
    ordering: false,
    columns: [
      {
        sClass: 'text-center',
        data: 'filepath',
        bSortable: false,
        render: function (data, type, full, meta) {
          return "<input type='checkbox' class='checkchild' onclick='checkboxClick()' id='" + data + "'" + '/>'
        },
      },
      {
        data: 'filepath',
        orderable: false,
        render: function (data, type, row, meta) {
          if (row.isfolder == 1) {
            return "<div><a href='javascript:void(0);' onclick='getdir(this.id)' id='" + data + "'><img src='/static/img/folder.png' onclick='getdir(this.id)'' id='" + data + "'>&ensp;" + row.filename + '</a></div>'
          } else {
            filetype = getFileType(data)
            return "<div><img src='/static/img/" + filetype + ".png'>&ensp;" + row.filename + '</div>'
          }
        },
      },
      { data: 'filesize',
        orderable: true,
        render: function (data, type, row, meta) {
          if (row.isfolder == 1) {
            return "<div><a style='color:#0040FF' href='javascript:void(0);' onclick='foldersize(this.id)' id='" + row.filepath + "'>" + "点击计算" + '</a></div>'
          } else {
            return data
          }
        },
      },
      {
        data: 'power',
        orderable: false,
        render: function (data, type, row, meta) {
          return "<div><a style='color:#0040FF' href='javascript:void(0);' onclick='chmod(this.id)' id='" + row.fileName + "'>" + data + '</a></div>'
        },
      },
      { data: 'filemodtime', orderable: true },
      {
        sClass: 'text-nowrap',
        data: null,
        orderable: false,
        render: function (data, type, row, meta) {
          var action_html = ''
          if (data.fileType != 'dir') {
            if (filetype == 'image') {
              action_html += "<a class='btn btn-primary btn-circle btn-sm'  href='javascript:void(0);' onclick='preview(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='预览'><i class='fas fa-image'></i></a>&ensp;"
            }
            if (filetype == 'zip') {
              action_html += "<a class='btn btn-primary btn-circle btn-sm'  href='javascript:void(0);' onclick='unzip(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='解压'><i class='fas fa-sticky-note'></i></a>&ensp;"
            }
            if(filetype=='radio'){
              //可以用aplay播放 https://github.com/DIYgod/APlayer
            }
            if(filetype=='video'){
              action_html += "<a class='btn btn-primary btn-circle btn-sm'  href='javascript:void(0);' onclick='play(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='播放'><i class='fas fa-play'></i></a>&ensp;"
            }
            action_html += "<a class='btn btn-primary btn-circle btn-sm' href='javascript:void(0);' onclick='textedit(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='编辑'><i class='fas fa-edit'></i></a>&ensp;"
            action_html += "<a class='btn btn-success btn-circle btn-sm'  href='javascript:void(0);' onclick='downfile(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='下载'><i class='fas fa-arrow-down'></i></a>&ensp;"
            action_html += "<a class='btn btn-info btn-circle btn-sm'  href='javascript:void(0);' onclick='fileShare(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='分享'><i class='fas fa-link'></i></a>&ensp;"
          } else {
            action_html += "<a class='btn btn-success btn-circle btn-sm'  href='javascript:void(0);' onclick='downfile(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='下载'><i class='fas fa-arrow-down'></i></a>&ensp;"
          }
          action_html += "<a class='btn btn-warning btn-circle btn-sm'  href='javascript:void(0);' onclick='renameFile(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='重命名'><i class='fas fa-undo'></i></a>&ensp;"
          action_html += "<a class='btn btn-danger btn-circle btn-sm'  href='javascript:void(0);' onclick='deletefile(this.id)' id='" + data.filepath + "' data-toggle='tooltip' title='删除'><i class='fas fa-trash'></i></a>&ensp;"
          return action_html
        },
      },
    ],
    language: language,
  })

  var t = $('#dataTable').DataTable()

  //列表全选
  $('.checkall').click(function () {
    var check = $(this).prop('checked')
    $('.checkchild').prop('checked', check)
    checkboxClick()
  })

  //点击文件更换目录
  function getdir(id) {
    var urldir = "{{ url_for('file.dir') }}" + '?path=' + Base64.encode(id)
    t.ajax.url(urldir).load() // 重载表格数据

    nowPath = id
    var nowpath=nowPath.replace(workPath,"")
    var pathtemplist = nowpath.split(sep)
    var fileRouteHtml = "<a href='javascript:void(0);' onclick='fileroute()' title='" + workPath + "' >全部文件</a>"
    $.each(pathtemplist, function (i, item) {
      if (item != '') {
        fileRouteHtml += "&gt;<a href='javascript:void(0);' onclick='fileroute()' title='" + item + "' >" + item + '</a>'
      }
    })
    document.getElementById('fileroute').innerHTML = fileRouteHtml
  }

  //点击上方目录结构切换目录
  function fileroute(id) {
    if (event.srcElement.title == workPath) {
      getdir(workPath)
    } else {
      var pathTempArr = nowPath.split(sep) //获取文件路径分离后的列表
      var clickText = event.srcElement.title //点击的文件夹
      var clickTextIndex = pathTempArr.indexOf(clickText) //点击的文件名在列表中的位置
      var clickFilePathArr = pathTempArr.slice(0, clickTextIndex + 1)
      var realPath = clickFilePathArr.join(sep)
      getdir(realPath)
    }
  }

  //下载文件
  function downfile(id) {
    var id = id
    var pathname = id.split(sep).pop()
    swal(
      {
        title: '操作提示',
        text: `是否下载名为“${pathname}”的文件？`,
        type: 'warning',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定下载！',
        cancelButtonText: '取消',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (isConfirm) {
        if (isConfirm) {
          id = Base64.encode(id)
          var exportForm = $('<form action="{{ url_for("file.download") }}" method="get"><input type="text" name="filename" id="inputBox" value="' + id + '"/></form>')
          $(document.body).append(exportForm)
          exportForm.submit()
          exportForm.remove()
        }
      }
    )
  }

  //重命名
  function renameFile(id) {
    var id = id
    var pathname = id.split(sep).pop()
    swal(
      {
        title: '操作提示',
        text: `正在更改“${pathname}”的文件名`,
        type: 'input',
        inputPlaceholder: '请输入新文件名',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定修改！',
        cancelButtonText: '取消',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (inputValue) {
        if (inputValue) {
          id = Base64.encode(id)
          name = Base64.encode(inputValue.replace(/[^\\\/]*[\\\/]+/g, ''))
          var param = { filename: id, newfilename: name }
          urlfor = "{{ url_for('file.rename') }}"
          $.ajax({
            url: urlfor,
            datatype: 'json',
            type: 'post',
            data: param,
            beforeSend:function(){
              loading()
            },
            complete: function () {
              removeLoading('test')
            },
            success: function (data) {
              if (data.code == 0) {
                t.ajax.reload(null, false)
                iziToast.success({
                  title: '成功',
                  message: '已经更改文件名',
                })
              } else {
                console.log(data)
                iziToast.warning({
                  title: '失败',
                  message: data.msg,
                })
              }
            },
            error: function (response) {
              console.log(response)
              iziToast.error({
                title: '出错了',
                message: '服务器返回了错误响应',
              })
            },
          })
        }
      }
    )
  }

  //删除
  function deletefile(id) {
    var id = id
    var pathname = id.split(sep).pop()
    swal(
      {
        title: '操作提示',
        text: `是否删除名为“${pathname}”的文件？`,
        type: 'warning',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定删除！',
        cancelButtonText: '取消',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (isConfirm) {
        if (isConfirm) {
          id = Base64.encode(id)
          var param = { filename: id }
          urlfor = "{{ url_for('file.delete') }}"
          $.ajax({
            url: urlfor,
            datatype: 'json',
            type: 'post',
            data: param,
            beforeSend:function(){
              loading()
            },
            complete: function () {
              removeLoading('test')
            },
            success: function (data) {
              if (data.code == 0) {
                t.ajax.reload(null, false)
                iziToast.success({
                  title: '成功',
                  message: '已经删除该文件',
                })
              } else {
                console.log(data)
                iziToast.warning({
                  title: '失败',
                  message: data.msg,
                })
              }
            },
            error: function (response) {
              console.log(response)
              iziToast.error({
                title: '出错了',
                message: '服务器返回了错误响应',
              })
            },
          })
        }
      }
    )
  }

  //计算大小
  function foldersize(id) {
    var elem=$(event.srcElement)
    var id = Base64.encode(id)
    var param = { "path": id}
    urlfor = "{{ url_for('file.size') }}"
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        elem.text("计算中...")
      },
      success: function (data) {
        if (data.code == 0) {
          elem.text(data.data)
          iziToast.success({
            title: '成功',
            message: '已经计算文件夹大小',
          })
        } else {
          elem.text('计算失败')
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        elem.text('计算失败')
        console.log(response)
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  }

  //权限
  function chmod(id) {
    var id = id
    var pathname = id.split(sep).pop()
    swal(
      {
        title: '操作提示',
        text: `正在更改“${pathname}”的权限`,
        type: 'input',
        inputPlaceholder: '请输入新权限',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定修改！',
        cancelButtonText: '取消',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (isConfirm) {
        if (isConfirm) {
          id = Base64.encode(id)
          var param = { filename: id, power: isConfirm }
          urlfor = "{{ url_for('file.chmod') }}"
          $.ajax({
            url: urlfor,
            datatype: 'json',
            type: 'post',
            data: param,
            beforeSend:function(){
              loading()
            },
            complete: function () {
              removeLoading('test')
            },
            success: function (data) {
              if (data.code == 0) {
                t.ajax.reload(null, false)
                iziToast.success({
                  title: '成功',
                  message: '已经获得新权限',
                })
              } else {
                console.log(data)
                iziToast.warning({
                  title: '失败',
                  message: data.msg,
                })
              }
            },
            error: function (response) {
              console.log(response)
              iziToast.error({
                title: '出错了',
                message: '服务器返回了错误响应',
              })
            },
          })
        }
      }
    )
  }

  //解压
  function unzip(id) {
    var id = id
    var pathname = id.split(sep).pop()
    swal(
      {
        title: '操作提示',
        text: `是否解压名为“${pathname}”的文件？`,
        type: 'warning',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定解压！',
        cancelButtonText: '取消',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (isConfirm) {
        if (isConfirm) {
          id = Base64.encode(id)
          var param = { filename: id }
          urlfor = "{{ url_for('file.unzip') }}"
          $.ajax({
            url: urlfor,
            datatype: 'json',
            type: 'post',
            data: param,
            beforeSend:function(){
              loading()
            },
            complete: function () {
              removeLoading('test')
            },
            success: function (data) {
              if (data.code == 0) {
                t.ajax.reload(null, false)
                iziToast.success({
                  title: '成功',
                  message: '已经解压到当前文件夹',
                })
              } else {
                console.log(data)
                iziToast.warning({
                  title: '失败',
                  message: data.msg,
                })
              }
            },
            error: function (response) {
              console.log(response)
              iziToast.error({
                title: '出错了',
                message: '服务器返回了错误响应',
              })
            },
          })
        }
      }
    )
  }

  //预览图片
  function preview(id) {
    //添加上传路径参数
    var path = Base64.encode(id)
    urlfor="{{ url_for('file.download') }}"
    $('#imageview').attr('src', urlfor+"?filename="+path)
    var viewer = new Viewer(document.getElementById('imageview'))
    $('#imageview').click()
  }

  //文本编辑控件
  var editor = CodeMirror.fromTextArea(document.getElementById('FunctionEditor'), {
    //mode: { name: 'text/x-cython', version: 2, singleLineStringErrors: false }, //实现python代码高亮
    lineNumbers: true, //显示行号
    tabSize: 4,
    indentUnit: 4, //  缩进
    //theme: 'darcula', //设置主题
    lineWrapping: true, //代码折叠
    foldGutter: true,
    gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
    matchBrackets: true, //括号匹配
    autoCloseBrackets: true,
    fullScreen: false, //全屏模式
    //styleActiveLine: true, // 当前行背景高亮
    //autoRefresh: true,
    // showHint: true,
    extraKeys: { 'Ctrl-Space': 'autocomplete' }, //ctrl-space唤起智能提示
  })

  //文本编辑
  function textedit(id) {
    //$('#myModal').modal()
    var dialog = $('#myModal').modal({
      backdrop: 'static', //指定一个静态的背景，当用户点击模态框外部时不会关闭模态框
      keyboard: true, //点击 escape 不会关闭模态窗口
      show: false, //初始化时不显示模态框
    })
    //var id=event.srcElement.id
    var id = Base64.encode(id)
    var param = { filename: id }
    var urlfor = "{{ url_for('file.edit') }}"
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        loading()
      },
      complete: function () {
        removeLoading('test')
      },
      success: function (data) {
        if (data.code == 0) {
          dialog.modal('show')
          $('#textTitle').text(id)
          editor.setValue(data.data)
          setTimeout(() => {
            editor.refresh()
          }, 500)
        } else {
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        console.log(response)
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  }

  //保存编辑的文本
  $('#submitText').on('click', function () {
    var id = $('#textTitle').text()
    var value = Base64.encode(editor.getValue())
    var param = { filename: id, data: value }
    var urlfor = "{{ url_for('file.save') }}"
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        loading()
      },
      complete: function () {
        removeLoading('test')
      },
      success: function (data) {
        if (data.code == 0) {
          $('#myModal').modal('hide')
          iziToast.success({
            title: '成功',
            message: '已经保存更改的文件到当前文件夹',
          })
        } else {
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        console.log(response)
        $('#myModal').modal('hide')
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  })

  //生成提取码
  $('#bulidcode').on('click', function () {
    $('#editcode').val(randomString(4))
  })

  //文件分享
  function fileShare(id) {
    $('#copylink').hide()
    $('#link').hide()
    var dialog = $('#myModalShare').modal({
      backdrop: 'static', //指定一个静态的背景，当用户点击模态框外部时不会关闭模态框
      keyboard: true, //点击 escape 不会关闭模态窗口
      show: false, //初始化时不显示模态框
    })
    dialog.modal('show')
    $('#editcode').val(randomString(4))
    $('#filenames').val(Base64.encode(id))
  }

  //生成链接
  $('#submitShare').on('click', function () {
    //$('#shareform').submit()
    $('#copylink').hide()
    $('#link').hide()

    var urlfor = "{{ url_for('share.create') }}"
    var param = $('#shareform').serializeObject()
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        loading()
      },
      complete: function () {
        removeLoading('test')
      },
      success: function (data) {
        if (data.code == 0) {
          $('#link').text(window.location.host + data.data)
          $('#link').attr('href', data.data)
          $('#link').show()
          $('#copylink').show()
        } else {
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        console.log(response)
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  })

  //打开上传窗口
  function upload(){
    var dialog = $('#myModalupload').modal({
      backdrop: 'static', //指定一个静态的背景，当用户点击模态框外部时不会关闭模态框
      keyboard: true, //点击 escape 不会关闭模态窗口
      show: false, //初始化时不显示模态框
    })
    dialog.modal('show')
    $('#uploads').html('点击此处进行上传')
    $('.progress-bar').css( 'width', '0%');
    $('.progress-bar').hide();
  }

  //开始上传
  $("#uploads").on("click", function() {
    $('#uploads').html('')
    $("#fileupload").click();
  });
  //上传过程处理
  $('#fileupload').fileupload({
    url : "{{ url_for('file.upload') }}",//请求发送的目标地址
    Type : 'POST',//请求方式 ，可以选择POST，PUT或者PATCH,默认POST
    dataType : 'json',//服务器返回的数据类型
    autoUpload : false,
    //formData:{"path":Base64.encode(nowPath)}
    //acceptFileTypes : /(gif|jpe?g|png)$/i,//验证图片格式
    //maxNumberOfFiles : 1,//最大上传文件数目
    //maxFileSize : 1000000, // 文件上限1MB
    //minFileSize : 100,//文件下限  100b
    // messages : {//文件错误信息
    //   acceptFileTypes : '文件类型不匹配',
    //   maxFileSize : '文件过大',
    //   minFileSize : '文件过小'
    // }
  })
  //图片添加完成后触发的事件
  .on("fileuploadadd", function(e, data) {
    //隐藏进度条
    $('.progress-bar').css( 'width', '0%');
    $('.progress-bar').hide();
    
    //获取上传路径并显示
    var filename=data.files[0]
    var filetype = getFileType(filename.name)
    var sizeformat=renderSize(filename.size)
    
    $('#uploads').append('<div class="mb-2"><img id="fileimg" src="/static/img/'+filetype+'.png" />'+filename.name+'（'+sizeformat+'）</div>')
    //绑定开始上传事件
    $('#submitUpload').click(function() {
      data.formData = {"path":Base64.encode(nowPath)};
      //添加上传路径参数
      jqXHR = data.submit();
      //解绑，防止重复执行
      $("#submitUpload").off("click"); 
    })
  })
  //当一个单独的文件处理队列结束触发(验证文件格式和大小)
  .on("fileuploadprocessalways", function(e, data) {
    //获取文件
    file = data.files[0];
    //获取错误信息
    if (file.error) {
      console.log(file.error);
    }
  })
  //显示上传进度条
  .on("fileuploadprogressall", function(e, data) {
    $('.progress-bar').show();
    var progress = parseInt(data.loaded / data.total * 100, 10); 
    $('.progress-bar').css( 
    'width',progress + '%'
    ); 
  })
  //上传请求失败时触发的回调函数
  .on("fileuploadfail", function(e, data) {
    iziToast.warning({
      title: '上传失败',
      message: data.errorThrown,
    })
  })
  //上传请求成功时触发的回调函数
  .on("fileuploaddone", function(e, data) {
    t.ajax.reload(null, false)
    iziToast.success({
      title: '上传成功',
      message: data.result,
    })
  })
  //上传请求结束后，不管成功，错误或者中止都会被触发
  .on("fileuploadalways", function(e, data) {
    //隐藏进度条
    $('.progress-bar').css( 'width', '0%');
    $('.progress-bar').hide();
  })

  //播放视频
  function play(id){
    var dialog = $('#myModalvideo').modal({
      //backdrop: 'static', //指定一个静态的背景，当用户点击模态框外部时不会关闭模态框
      keyboard: true, //点击 escape 会关闭模态窗口
      show: false, //初始化时不显示模态框
    })
    //添加上传路径参数
    var path = Base64.encode(id)
    urlfor="{{ url_for('file.download') }}"
    $('#my-player').attr('src', urlfor+"?filename="+path);
    dialog.modal('show')
  }
  //关闭时停止播放
  $('#myModalvideo').on('hidden.bs.modal', function () {
    $('#my-player').attr('src', '');
  })

  //新建空白文件夹
  function mkdir() {
    swal(
      {
        title: '操作提示',
        text: `正在新建空白文件夹`,
        type: 'input',
        inputPlaceholder: '请输入新文件夹名',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定创建！',
        cancelButtonText: '取消',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (inputValue) {
        if (inputValue) {
          var id = Base64.encode(nowPath)
          var name = Base64.encode(inputValue.replace(/[^\\\/]*[\\\/]+/g, ''))
          var param = { path: id, foldername: name }
          urlfor = "{{ url_for('file.mkdir') }}"
          $.ajax({
            url: urlfor,
            datatype: 'json',
            type: 'post',
            data: param,
            beforeSend:function(){
              loading()
            },
            complete: function () {
              removeLoading('test')
            },
            success: function (data) {
              if (data.code == 0) {
                t.ajax.reload(null, false)
                iziToast.success({
                  title: '成功',
                  message: '已经在当前文件夹创建新文件夹',
                })
              } else {
                console.log(data)
                iziToast.warning({
                  title: '失败',
                  message: data.msg,
                })
              }
            },
            error: function (response) {
              console.log(response)
              iziToast.error({
                title: '出错了',
                message: '服务器返回了错误响应',
              })
            },
          })
        }
      }
    )
  }

  //新建空白文件
  function touch(){
    swal(
      {
        title: '操作提示',
        text: `正在新建空白文件`,
        type: 'input',
        inputPlaceholder: '请输入新文件名',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定创建！',
        cancelButtonText: '取消',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (inputValue) {
        if (inputValue) {
          var id = Base64.encode(nowPath)
          var name = Base64.encode(inputValue.replace(/[^\\\/]*[\\\/]+/g, ''))
          var param = { path: id, filename: name }
          urlfor = "{{ url_for('file.touch') }}"
          $.ajax({
            url: urlfor,
            datatype: 'json',
            type: 'post',
            data: param,
            beforeSend:function(){
              loading()
            },
            complete: function () {
              removeLoading('test')
            },
            success: function (data) {
              if (data.code == 0) {
                t.ajax.reload(null, false)
                iziToast.success({
                  title: '成功',
                  message: '已经在当前文件夹新建空白文件',
                })
              } else {
                console.log(data)
                iziToast.warning({
                  title: '失败',
                  message: data.msg,
                })
              }
            },
            error: function (response) {
              console.log(response)
              iziToast.error({
                title: '出错了',
                message: '服务器返回了错误响应',
              })
            },
          })
        }
      }
    )
  }

  //复制
  function copy(){
    var filename=[]
    for(var i=0;i<$(".checkchild:checked").length;i++){
      filename[i]=Base64.encode($($(".checkchild:checked")[i]).attr('id'))
    }
    var param = { "filenames": JSON.stringify(filename) }
    var urlfor = "{{ url_for('file.copy') }}"
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        loading()
      },
      complete: function () {
        removeLoading('test')
      },
      success: function (data) {
        if (data.code == 0) {
          $("#paste").show()
          iziToast.success({
            title: '成功',
            message: '已经复制选中文件到剪切板',
          })
        } else {
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        console.log(response)
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  }

  //剪切
  function cut(){
    var filename=[]
    for(var i=0;i<$(".checkchild:checked").length;i++){
      filename[i]=Base64.encode($($(".checkchild:checked")[i]).attr('id'))
    }
    var param = { "filenames": JSON.stringify(filename) }
    var urlfor = "{{ url_for('file.cut') }}"
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        loading()
      },
      complete: function () {
        removeLoading('test')
      },
      success: function (data) {
        if (data.code == 0) {
          $("#paste").show()
          iziToast.success({
            title: '成功',
            message: '已经剪切选中文件到剪切板',
          })
        } else {
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        console.log(response)
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  }

  //压缩
  function zip(){
    var filename=[]
    for(var i=0;i<$(".checkchild:checked").length;i++){
      filename[i]=Base64.encode($($(".checkchild:checked")[i]).attr('id'))
    }
    var value = Base64.encode(nowPath)
    var param = { "filenames": JSON.stringify(filename), "path":value}
    var urlfor = "{{ url_for('file.zip') }}"
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        loading()
      },
      complete: function () {
        removeLoading('test')
      },
      success: function (data) {
        if (data.code == 0) {
          t.ajax.reload(null, false)
          iziToast.success({
            title: '成功',
            message: '已经压缩选中文件到当前文件夹',
          })
        } else {
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        console.log(response)
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  }

  //删除多个
  function deletes(){
    swal(
      {
        title: '操作提示',
        text: `是否删除选中的文件？`,
        type: 'warning',
        showCancelButton: true,
        showLoaderOnConfirm: true,
        confirmButtonColor: '#4D9BFF',
        confirmButtonText: '是的，确定删除！',
        cancelButtonText: '关闭',
        closeOnConfirm: true,
        closeOnCancel: true, //关闭取消后还弹出让你确认的效果提示
        timer: 200,
      },
      function (isConfirm) {
        if(isConfirm){
          var filename=[]
          for(var i=0;i<$(".checkchild:checked").length;i++){
            filename[i]=Base64.encode($($(".checkchild:checked")[i]).attr('id'))
          }
          //var value = Base64.encode(nowPath)
          var param = { "filenames": JSON.stringify(filename)}
          var urlfor = "{{ url_for('file.deletes') }}"
          $.ajax({
            url: urlfor,
            datatype: 'json',
            type: 'post',
            data: param,
            beforeSend:function(){
              loading()
            },
            complete: function () {
              removeLoading('test')
            },
            success: function (data) {
              if (data.code == 0) {
                t.ajax.reload(null, false)
                iziToast.success({
                  title: '成功',
                  message: '已经删除选中文件',
                })
              } else {
                console.log(data)
                iziToast.warning({
                  title: '失败',
                  message: data.msg,
                })
              }
            },
            error: function (response) {
              console.log(response)
              iziToast.error({
                title: '出错了',
                message: '服务器返回了错误响应',
              })
            },
          })
        }
      }
    )
  }

  //粘贴
  function paste(){
    var value = Base64.encode(nowPath)
    var param = { "path": value}
    var urlfor = "{{ url_for('file.paste') }}"
    $.ajax({
      url: urlfor,
      datatype: 'json',
      type: 'post',
      data: param,
      beforeSend:function(){
        loading()
      },
      complete: function () {
        removeLoading('test')
      },
      success: function (data) {
        if (data.code == 0) {
          t.ajax.reload(null, false)
          iziToast.success({
            title: '成功',
            message: '已经把剪切板文件粘贴到当前为文件夹',
          })
        } else {
          console.log(data)
          iziToast.warning({
            title: '失败',
            message: data.msg,
          })
        }
      },
      error: function (response) {
        console.log(response)
        iziToast.error({
          title: '出错了',
          message: '服务器返回了错误响应',
        })
      },
    })
  }

  $("#actiondropdown").hide()
  //多选操作
  function checkboxClick(){
    //获取选中的某一个checkbox的值
    if ($(".checkchild:checked").length >= 1){
      $("#actiondropdown").show()
      return
    }
    $("#actiondropdown").hide()
  }

  //复制到剪切板
  var clipboard = new ClipboardJS('#copylink', {
    //Bootstrap Modals中使用或与任何其他更改焦点的库一起使用，您需要将focus元素设置为container值
    container: document.getElementById('myModalShare'),
    text: function (trigger) {
      var link = $('#link').text()
      var getcode = $('input[name="getcode"]').val()
      var texts = '链接: ' + link + ' 提取码: ' + getcode
      return texts
    },
  })
  clipboard.on('success', function (e) {
    console.log(e)
    iziToast.success({
      title: '成功',
      message: '链接和提取码已经复制到剪切板',
    })
  })
  clipboard.on('error', function (e) {
    console.log(e)
    iziToast.error({
      title: '失败',
      message: '浏览器不支持复制到剪切板',
    })
  })
</script>
{% endblock %}
